<?php
/**
 * JS_API支付demo
 * ====================================================
 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
 * 成功调起支付需要三个步骤：
 * 步骤1：网页授权获取用户openid
 * 步骤2：使用统一支付接口，获取prepay_id
 * 步骤3：使用jsapi调起支付
*/
	include_once("../WxPayPubHelper/WxPayPubHelper.php");
	include 'conn_mysql.php';
	
	//使用jsapi接口
	$jsApi = new JsApi_pub();

	//=========步骤1：网页授权获取用户openid============
	//通过code获得openid
	if (!isset($_GET['code']))
	{
		$monkey			=		$_REQUEST['monkey'];
		$miaoshu        =       $_REQUEST['miaoshu'];
		$ke_lvbi        =       $_REQUEST['ke_lvbi'];

		$id_main        =       $_REQUEST['id_main'];//订单ID
        

		
		//触发微信返回code码
		$url = $jsApi->createOauthUrlForCode(urlencode(WxPayConf_pub::JS_API_CALL_URL),"$monkey"."_"."$miaoshu"."_"."$ke_lvbi"."_"."$id_main");
		header("Location: $url"); 
		exit;
	}else
	{	
		$state			=		$_REQUEST['state'];
		$arr            =       explode('_',$state);
		$monkey			=		$arr[0];
		$miaoshu        =       $arr[1];
		$ke_lvbi          =     $arr[2];
		$id_main          =     $arr[3];

		//	//以订单获取要付的金额
		$sql="SELECT is_zhifu FROM `main_user` WHERE id_self='".$id_main."'";
		$query = mysql_query($sql);
		$row = mysql_fetch_array($query);
		$is_zhifu=$row['is_zhifu'];
		 //处理返回无效
		if($is_zhifu==1){echo "<script>location.href='http://haining.365jinbi.com/lvxingtianxia/lvyou_list.php';</script>";exit;}
		
		//获取code码，以获取openid
	    $code = $_GET['code'];
		$jsApi->setCode($code);
		$openid = $jsApi->getOpenId();
	}

     //必须选择游客
		$sql="select id_fu from fu_user where id='$id_main' ";
		$query = mysql_query($sql);
		while($row = mysql_fetch_array($query)){
			$id_fu=$row['id_fu'];
		}

		if(!$id_fu)
		{
			echo "<script>alert('请添加或者选择游客');history.go(-1)</script>";exit;
		}

	//检测拥有驴币
	$user_id=$_SESSION['user_id'];
	$sql="SELECT pay_points FROM `ecs_users` WHERE user_id='".$user_id."'";
	$query = mysql_query($sql);
	$row = mysql_fetch_array($query);
	$pay_points=$row[0]?$row[0]:0;
	if($pay_points<$ke_lvbi)
	{
		echo "<script>alert('你拥有的驴币没那么多');history.go(-1)</script>";exit;
	}

    //zhsk消耗多少驴币
	$sql="update  `main_user`  set pay_points='$ke_lvbi' WHERE  id_self='".$id_main."'";
	$query = mysql_query($sql);
	//以订单获取要付的金额
	$sql="SELECT zhifu_monkey FROM `main_user` WHERE id_self='".$id_main."'";
	$query = mysql_query($sql);
	$row = mysql_fetch_array($query);

	$ke_lvbi=$ke_lvbi?$ke_lvbi:0;
	if($row[0]-$ke_lvbi==0)$monkey=1;
	else $monkey=($row[0]-$ke_lvbi)*100;

	
	//=========步骤2：使用统一支付接口，获取prepay_id============
	//使用统一支付接口
	$unifiedOrder = new UnifiedOrder_pub();
	
	//设置统一支付接口参数
	//设置必填参数
	//appid已填,商户无需重复填写
	//mch_id已填,商户无需重复填写
	//noncestr已填,商户无需重复填写
	//spbill_create_ip已填,商户无需重复填写
	//sign已填,商户无需重复填写
	$unifiedOrder->setParameter("openid","$openid"); 
	$unifiedOrder->setParameter("body","$miaoshu");//商品描述
	//自定义订单号，此处仅作举例
	$timeStamp = time();
	// $out_trade_no = WxPayConf_pub::APPID."$timeStamp";

	$out_trade_no = $timeStamp."P".$id_main;
	
	//将给订单号绑定给用户对应的手机	
	$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 
	$unifiedOrder->setParameter("total_fee","$monkey");//总金额
	$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址 
	$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
	//非必填参数，商户可根据实际情况选填
	//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
	//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
	//$unifiedOrder->setParameter("attach","XXXX");//附加数据 
	//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
	//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
	//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
	//$unifiedOrder->setParameter("openid","XXXX");//用户标识
	//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

	$prepay_id = $unifiedOrder->getPrepayId();
	//=========步骤3：使用jsapi调起支付============
	$jsApi->setPrepayId($prepay_id);

	$jsApiParameters = $jsApi->getParameters();
	//echo $jsApiParameters;
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
	 <meta name="viewport" content="width=device-width, maximum-scale=1, user-scalable=no">
    <title>微信安全支付</title>

	<script type="text/javascript">

		//调用微信JS api 支付
		function jsApiCall()
		{
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest',
				<?php echo $jsApiParameters; ?>,
				function(res){
					WeixinJSBridge.log(res.err_msg);
					//alert("微信支付成功，进行页面跳转！");
					  if(res.err_msg == "get_brand_wcpay_request:ok"){  
						   window.location.href='http://haining.365jinbi.com/lvxingtianxia/index_pay.php?order_id=<?php echo $id_main;?>&is_zhifu=1&ke_lvbi=<?php echo $ke_lvbi;?>';  
					   }else if(res.err_msg == "get_brand_wcpay_request:cancel"){  
						   window.location.href='http://haining.365jinbi.com/lvxingtianxia/index_pay.php';  
					   }else{  
						   window.location.href='http://haining.365jinbi.com/lvxingtianxia/index_pay.php'; 
					   }  
				}
			);
		}

		function callpay()
		{
			if (typeof WeixinJSBridge == "undefined"){
			    if( document.addEventListener ){
			        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			    }else if (document.attachEvent){
			        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
			        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			    }
			}else{
			    jsApiCall();
			}
		}
	</script>
</head>
<body>
	</br></br></br></br>
	<div align="center">
		<p style="font-size:16px;">交易描述：<?php echo $miaoshu;?></p>
		<p style="font-size:16px;">总金额：<?php echo ($monkey/100)."元";?></p>
		<p style="font-size:16px;">交易时间：<?php echo date('Y-m-d H:i:s',time());?></p>
		<button style="border-radius: 6px;background-color: #ff0000;color: white;font-size: 18px;width: 100%;line-height: 40px;border: none;" type="button" onclick="callpay()" >支付</button>
	</div>
</body>
</html>